import { ref } from 'vue'
import type { GetUserPermissionResult } from '@/api/modules/permission'

// 用户权限数据
export const userPermissions = ref<GetUserPermissionResult['permissions'] | null>(null)

// 前后端权限键名映射
const permissionKeyMap: Record<string, string> = {
  'home': 'homeManagement',
  'publish-management': 'publishManagement',
  'short-video-management': 'shortVideoManagement',
  'private-message-management': 'privateChatManagement',
  'user-management': 'userManagement',
  'file-management': 'uploadManagement',
  'notification-management': 'systemNotificationManagement',
  'log-management': 'logManagement',
  'permission-management': 'permissionManagement',
  'industry-map': 'industryMapManagement'
}

/**
 * 设置用户权限
 * @param permissions 权限数据
 */
export function setUserPermissions(permissions: GetUserPermissionResult['permissions']) {
  userPermissions.value = permissions
}

/**
 * 检查指定分类的页面是否应该显示
 * @param categoryKey 分类键名
 * @returns boolean 是否显示
 */
export function isPageVisible(categoryKey: string): boolean {
  // 如果没有权限数据，默认显示所有页面
  if (!userPermissions.value) {
    return true
  }
  // 获取映射后的键名
  const mappedKey = permissionKeyMap[categoryKey] || categoryKey
  
  // 检查指定分类是否存在且pageShow为true
  const category = userPermissions.value[mappedKey]

  return category ? category.pageShow : true
}

/**
 * 检查是否有指定权限
 * @param categoryKey 分类键名
 * @param permissionKey 权限键名
 * @returns boolean 是否有权限
 */
export function hasPermission(categoryKey: string, permissionKey: string): boolean {
  // 如果没有权限数据，默认有权限
  if (!userPermissions.value) {
    return true
  }
  
  // 获取映射后的键名
  const mappedKey = permissionKeyMap[categoryKey] || categoryKey
  
  // 检查指定分类和权限是否存在且为true
  const category = userPermissions.value[mappedKey]
  if (!category) return false
  
  const permission = category.permissions[permissionKey]
  return permission ? permission.value : false
}